package io.renren.modules.mvs.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.mvs.dto.PaymentForm;
import io.renren.modules.mvs.entity.TicketEntity;
import io.renren.modules.mvs.entity.ViolationEntity;
import io.renren.modules.mvs.entity.ViolationTypeEntity;
import io.renren.modules.mvs.service.TicketService;
import io.renren.modules.mvs.service.ViolationService;
import io.renren.modules.mvs.service.ViolationTypeService;
import io.renren.modules.sys.controller.AbstractController;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

import static io.renren.common.utils.Constant.UNPAID;
import static io.renren.common.utils.MvsUtils.calculateOverDueFee;


/**
 * 罚单表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2025-03-30 17:08:24
 */
@RestController
@RequestMapping("mvs/ticket")
@Log4j2
public class TicketController extends AbstractController {
    @Autowired
    private TicketService ticketService;
    @Autowired
    private ViolationService violationService;
    @Autowired
    private ViolationTypeService violationTypeService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @RequiresPermissions("mvs:ticket:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = ticketService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("mvs:ticket:info")
    public R info(@PathVariable("id") String id) {
        TicketEntity ticket = ticketService.getById(id);
        return R.ok().put("ticket", ticket);
    }

    /**
     * 保存
     */
    @SysLog("新增罚单")
    @PostMapping("/save")
    @RequiresPermissions("mvs:ticket:save")
    public R save(@RequestBody TicketEntity ticket) {
        //1.根据违章记录id查询违章记录表
        ViolationEntity violation = violationService.getById(ticket.getViolationId());
        //2.根据违章类型id查询罚金等信息
        ViolationTypeEntity violationType = violationTypeService.getById(violation.getViolationTypeId());
        //3.根据违章信息获取罚单需要的其它数据
        //3.1 计算违章天数
        LocalDate localDate = violation.getViolationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        long dayNumber = ChronoUnit.DAYS.between(localDate, LocalDate.now());
        ticket.setViolationDay((int) (dayNumber < 0 ? 0 : dayNumber));
        //3.2 罚金
        BigDecimal fineAmount = violationType.getFineAmount();
        ticket.setFineAmount(fineAmount);
        ticket.setWaitFine(fineAmount);
        //3.3 计算滞纳金
        BigDecimal overdueFee = calculateOverDueFee(violation.getViolationDeadline(), fineAmount);
        ticket.setOverdueFee(overdueFee);
        //3.4 代缴滞纳金和罚单状态
        ticket.setWaitOverdueFee(overdueFee);
        ticket.setTicketStatus(UNPAID);
        //3.4 罚单创建日期
        ticket.setCreateTime(new Date());

        ticketService.save(ticket);
        return R.ok();
    }

    /**
     * 修改
     */
    /*@SysLog("修改罚单")
    @RequestMapping("/update")
    @RequiresPermissions("mvs:ticket:update")
    public R update(@RequestBody TicketEntity ticket) {
        ticketService.updateById(ticket);
        return R.ok();
    }*/

    /**
     * 删除
     */
    @SysLog("删除罚单")
    @RequestMapping("/delete")
    @RequiresPermissions("mvs:ticket:delete")
    public R delete(@RequestBody String[] ids) {
        ticketService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 根据罚单id查询需要缴费的罚单信息
     */
    @GetMapping("/info/payment/{id}")
    @RequiresPermissions("mvs:ticket:info")
    public R waitPaymentInfo(@PathVariable String id) {
        TicketEntity ticket = ticketService.getByWaitPayment(id);
        if (ticket == null) {
            return R.error("不存在该罚单或该罚单无需缴费");
        }
        return R.ok().put("ticket", ticket);
    }

    /**
     * 缴费
     */
    @SysLog("缴费")
    @PostMapping("/payment")
    @RequiresPermissions("mvs:ticket:payment")
    public R payment(@RequestBody PaymentForm paymentForm) {
        BigDecimal payMoney = paymentForm.getPayMoney();
        if (payMoney.compareTo(BigDecimal.ZERO) <= 0) {
            return R.error("缴费金额不能小于零");
        }
        BigDecimal surplus = ticketService.payment(payMoney, paymentForm.getTicketId(), getUserId());
        if (surplus.compareTo(BigDecimal.ZERO) > 0) {
            return R.ok("缴费成功，多余金额" + surplus + "元已退回");
        }
        return R.ok("缴费成功");
    }

    /**
     * 获取指定日期范围内每日的罚款金额
     */
    @GetMapping("/list/fine")
    @RequiresPermissions("mvs:ticket:list")
    public R fineListByDateRange(@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate) {
        Map<String, Collection<?>> dataMap = ticketService.getFineListByDateRange(startDate, endDate);
        return R.ok().put("dataMap", dataMap);
    }

    /**
     * 获取指定日期范围内每日的总欠款金额
     */
    @GetMapping("/list/money")
    @RequiresPermissions("mvs:ticket:list")
    public R moneyListByDateRange(@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate) {
        Map<String, Collection<?>> dataMap = ticketService.getMoneyListByDateRange(startDate, endDate);
        return R.ok().put("dataMap", dataMap);
    }
}
